import {Http} from "./http";

class Paging {
    req // 请求参数 {url,data,method}
    start
    count
    locker = false
    url
    hasMore = true
    accumulator = []

    constructor(req, start = 0, count = 10) {
        this.req = req
        this.start = start
        this.count = count
        this.url = req.url
    }

    async getMoreData() {
        // 没有更多数据
        if (!this.hasMore) return
        if (!this._getLocker()) return
        const data = await this._doGetMoreData()
        this._releaseLocker()
        return data
    }

    async _doGetMoreData() {
        const req = this._getCurrentReq()
        let paging = await Http.request(req)
        if (!paging) return

        if (paging.total === 0) {
            return {
                empty: true,
                items: [], // 当前请求到的数据
                hasMore: false,
                accumulator: [] // 历史数据累加
            }
        }
        // page当前页 total_page总页数
        this.hasMore = paging.page < paging.total_page - 1

        if (this.hasMore) {
            this.start += this.count
        }
        // 数组累加
        this.accumulator = this.accumulator.concat(paging.items)
        return {
            empty: false,
            items: paging.items, // 当前请求到的数据
            hasMore: this.hasMore,
            accumulator: this.accumulator // 历史数据累加
        }
    }

    // 拼接url,防止参数重复拼接
    _getCurrentReq() {
        let url = this.url
        const params = `start=${this.start}&count=${this.count}`
        if (url.includes("?")) {
            url += '&' + params
        } else {
            url += '?' + params
        }
        this.req.url = url
        return this.req
    }

    // 标识符,防止重复请求
    _getLocker() {
        // 锁住的时候获取不到锁
        if (this.locker) return false
        this.locker = true
        return true
    }

    _releaseLocker() {
        this.locker = false
    }

}

export {
    Paging
}
